package com.kongjs.application.component;

import com.kongjs.application.model.dto.RoleCacheDTO;
import com.kongjs.application.model.dto.UserCacheDTO;
import com.kongjs.application.cache.UserCacheManager;
import com.kongjs.common.mybatis.tenant.TenantContextHolder;
import com.kongjs.common.mybatis.user.UserContextHolder;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.util.CollectionUtils;
import org.springframework.util.NumberUtils;
import org.springframework.util.ObjectUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Slf4j
//@Component
public class JwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> {

    @Resource
    private UserCacheManager userCacheManager;

    @Override
    public Collection<GrantedAuthority> convert(Jwt jwt) {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        String userId = jwt.getClaimAsString("userId");
        try {
            Long id = NumberUtils.parseNumber(userId, Long.class);
            UserCacheDTO userCache = userCacheManager.loadUserCache(id);
            if (ObjectUtils.isEmpty(userCache) || ObjectUtils.isEmpty(userCache.getEnabled()) || userCache.getEnabled().equals(0)) {
                return grantedAuthorities;
            }
            TenantContextHolder.setTenantId(String.valueOf(userCache.getTenantId()));
            UserContextHolder.setUserId(String.valueOf(userCache.getId()));
            Set<Long> roleIds = userCache.getRoleIds();
            if (CollectionUtils.isEmpty(roleIds)) {
                return grantedAuthorities;
            }
            Map<Long, RoleCacheDTO> roleCacheMap = userCacheManager.loadRoleCache(roleIds);
            for (RoleCacheDTO roleCache : roleCacheMap.values()) {
                if (ObjectUtils.isEmpty(roleCache.getEnabled()) || roleCache.getEnabled().equals(0)) {
                    continue;
                }
                grantedAuthorities.add(new SimpleGrantedAuthority(roleCache.getAuthority()));
            }
        } catch (Exception e) {
            log.error("加载jwt权限异常 {}", e.getMessage());
        }
        return grantedAuthorities;
    }
}
